package second.graph;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution09 {
    LinkedList<int[]> queue = new LinkedList<>();

    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        int m = heights.length;
        int n = heights[0].length;
        boolean[][] pac = new boolean[m][n];
        boolean[][] atl = new boolean[m][n];
        for (int i = 0; i < n; i++) {
            bfs(heights, 0, i, pac);
            bfs(heights, m - 1, i, atl);
        }
        for (int i = 1; i < m; i++) {
            bfs(heights, i, 0, pac);
            bfs(heights, m - 1 - i, n - 1, atl);
        }
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (pac[i][j] && atl[i][j]) {
                    List<Integer> tmp = new ArrayList<>();
                    tmp.add(i);
                    tmp.add(j);
                    res.add(tmp);
                }
            }
        }
        return res;
    }

    public void bfs(int[][] heights, int x, int y, boolean[][] reach) {
        if (reach[x][y]) return;
        queue.add(new int[]{x, y});
        while (!queue.isEmpty()) {
            int[] cur = queue.removeFirst();
            int i = cur[0];
            int j = cur[1];
            reach[i][j] = true;
            if (i - 1 >= 0 && heights[i - 1][j] >= heights[i][j] && !reach[i - 1][j]) queue.add(new int[]{i - 1, j});
            if (i + 1 < heights.length && heights[i + 1][j] >= heights[i][j] && !reach[i + 1][j])
                queue.add(new int[]{i + 1, j});
            if (j - 1 >= 0 && heights[i][j - 1] >= heights[i][j] && !reach[i][j - 1]) queue.add(new int[]{i, j - 1});
            if (j + 1 < heights[0].length && heights[i][j + 1] >= heights[i][j] && !reach[i][j + 1])
                queue.add(new int[]{i, j + 1});
        }
    }
}

